package com.liwy3.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.cloud.gateway.filter.factory.rewrite.ModifyRequestBodyGatewayFilterFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.Map;


/**
 * Copyright © 元气森林（北京）食品科技集团有限公司. All rights reserved.
 *
 * @Description:
 * @author: Crazy4J
 * @date: 2022年02月16日 10:10
 * @version: V1.0
 */
@Component
@Slf4j
public class FxiaokeGatewayFilterFactory extends AbstractGatewayFilterFactory<FxiaokeGatewayFilterFactory.Config> {

    private static final String CONTENT_TYPE = "Content-Type";

    public FxiaokeGatewayFilterFactory() {
        super(FxiaokeGatewayFilterFactory.Config.class);
    }

    @Override
    public GatewayFilter apply(FxiaokeGatewayFilterFactory.Config config) {
        return (exchange, chain) -> {

            ServerHttpRequest request = exchange.getRequest();
            String contentType = request.getHeaders().getFirst(CONTENT_TYPE);
            String method = request.getMethodValue();

            if (null != contentType && HttpMethod.POST.name().equalsIgnoreCase(method) && contentType.contains(MediaType.APPLICATION_JSON_VALUE)) {

                ModifyRequestBodyGatewayFilterFactory.Config modifyRequestConfig = new ModifyRequestBodyGatewayFilterFactory.Config()
                        .setRewriteFunction(Map.class, Map.class, (exchangeT, originalRequestBody) -> {
                            //修改请求体数据
                            modifyFxiaokeBody(originalRequestBody);
                            return Mono.just(originalRequestBody);
                        });

                return new ModifyRequestBodyGatewayFilterFactory().apply(modifyRequestConfig).filter(exchange, chain);
            }

            return chain.filter(exchange);
        };
    }

    /**
     * 修改分享body参数信息
     */
    private void modifyFxiaokeBody(Map originalRequestBody) {
        Object token = originalRequestBody.get("token");
        log.info("网关接受token: {}, 分享token:{}",token,"WOSHI666");
        originalRequestBody.put("token", "WOSHI666");
    }

    static class Config {

    }



}
